package com.tanhua.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.exception.BusinessException;
import com.tanhua.interceptor.UserHolder;
import model.domain.User;
import model.domain.UserInfo;
import model.mongo.Friend;
import model.vo.ContactVo;
import model.vo.ErrorResult;
import model.vo.PageResult;
import model.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {
    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;


    public UserInfoVo findUserInfoByHuanXinId(String huanxinId) {
        User user = userApi.findUserByHuanXinId(huanxinId);

        UserInfo userInfo = userInfoApi.findById(user.getId());

        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo); //copy同名同类型的属性
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    public void contacts(Long friendId) {
        Boolean aBoolean = huanXinTemplate.addContact(
                Constants.HX_USER_PREFIX + UserHolder.getUserId(),
                Constants.HX_USER_PREFIX + friendId);
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }
        friendApi.save(UserHolder.getUserId(), friendId);
    }

    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        List<Friend> friends = friendApi.findByUserId(UserHolder.getUserId(), page, pagesize);
        if (CollUtil.isEmpty(friends)) {
            return new PageResult();
        }
        List<Long> friendIds = CollUtil.getFieldValues(friends, "friendId", Long.class);

        Map<Long, UserInfo> friendInfoMap = userInfoApi.findByIds(friendIds, new UserInfo().setNickname(keyword));
        List<ContactVo> contactVos = new ArrayList<>();
        for (Friend friend : friends) {
            UserInfo friendInfo = friendInfoMap.get(friend.getFriendId());
            if (friendInfo != null) {
                ContactVo contactVo = ContactVo.init(friendInfo);
                contactVos.add(contactVo);
            }
        }
        return new PageResult(page, pagesize, 0l, contactVos);
    }
}
